<template>
  <!-- 游戏布局 -->
  <div class="min-h-screen bg-gradient-to-br from-blue-100 via-gray-100 to-pink-100 flex overflow-hidden">
    <!-- 左侧内容区域 -->
    <div class="w-3/4 p-4 overflow-y-auto max-h-screen pb-20">
      <h1 class="text-3xl font-extrabold text-center mb-3 text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-pink-500">人工测试</h1>
      
      <!-- 卡牌计数显示 - 添加在最顶部 -->
      <div class="mb-3 bg-white/90 rounded-xl shadow-md p-2 sticky top-0 z-10">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-2">
            <span class="text-xs font-semibold text-gray-500">已发牌:</span>
            <div class="text-sm font-bold" :class="remainingDeals <= 10 ? 'text-red-500' : 'text-gray-700'">
              {{ cardsDealtCount }} / {{ maxCardsLimit }}
            </div>
          </div>
          <div class="flex items-center space-x-2">
            <span class="text-xs font-semibold text-gray-500">剩余发牌次数:</span>
            <div class="text-sm font-bold" :class="remainingDeals <= 10 ? 'text-red-500' : 'text-green-500'">
              {{ remainingDeals }}
            </div>
          </div>
          <div v-if="gameEnded" class="text-sm font-bold text-red-500">
            游戏已结束！达到最大发牌数量限制
          </div>
        </div>
      </div>
      
      <!-- 历史牌记录 - 放在顶部 -->
      <div class="mb-3 bg-white/90 rounded-xl shadow-md p-2 overflow-x-auto">
        <div class="flex items-center space-x-1">
          <span class="text-xs font-semibold text-gray-500 whitespace-nowrap mr-2">历史牌:</span>
          <div class="flex space-x-3">
            <div v-for="(record, index) in history.slice(0, 10)" :key="index" class="flex items-center">
              <div class="flex flex-col items-center">
                <div class="text-xs font-semibold" :class="record.result === 'banker' ? 'text-red-500' : (record.result === 'player' ? 'text-blue-500' : 'text-green-500')">
                  {{ translateResult(record.result) }}
                </div>
                <div class="flex space-x-1">
                  <div class="text-xs bg-blue-50 px-1 rounded">
                    {{ record.player_points }}
                  </div>
                  <div class="text-xs bg-pink-50 px-1 rounded">
                    {{ record.banker_points }}
                  </div>
                </div>
              </div>
              <span v-if="index < history.slice(0, 10).length - 1" class="text-gray-300 mx-1">|</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输赢合计 -->
      <div class="mb-3 text-center">
        <h2 class="text-lg font-semibold mb-1 text-gray-700">总输赢</h2>
        <p class="text-2xl font-bold" :class="totalWinLoss > 0 ? 'text-green-600' : (totalWinLoss < 0 ? 'text-red-500' : 'text-gray-500')">
          {{ totalWinLoss > 0 ? '+' : '' }}{{ totalWinLoss.toFixed(2) }}
        </p>
      </div>
      
      <div class="grid grid-cols-2 gap-4">
        <!-- 游戏状态 -->
        <div class="mb-4">
          <h2 class="text-lg font-semibold mb-2 text-gray-700">当前回合</h2>
          <div class="space-y-3">
            <div class="p-4 rounded-xl shadow bg-gradient-to-br from-blue-100 to-blue-50 flex flex-col items-center">
              <h3 class="font-bold text-blue-700 mb-1">闲家</h3>
              <div v-if="playerHand.length === 0" class="w-24 h-16 rounded-xl bg-gradient-to-r from-blue-300 to-blue-100 animate-pulse mb-1"></div>
              <div v-else class="flex items-center space-x-2 mb-1">
                <span v-for="(card, idx) in playerHand" :key="idx" 
                      class="text-lg font-mono py-1 px-2 bg-white rounded border border-blue-200 shadow-sm">
                  {{ card }}
                </span>
              </div>
              <p class="text-sm text-gray-600">点数: <span class="font-bold">{{ playerPoints }}</span></p>
            </div>
            <div class="p-4 rounded-xl shadow bg-gradient-to-br from-pink-100 to-pink-50 flex flex-col items-center">
              <h3 class="font-bold text-pink-700 mb-1">庄家</h3>
              <div v-if="bankerHand.length === 0" class="w-24 h-16 rounded-xl bg-gradient-to-r from-pink-300 to-pink-100 animate-pulse mb-1"></div>
              <div v-else class="flex items-center space-x-2 mb-1">
                <span v-for="(card, idx) in bankerHand" :key="idx" 
                      class="text-lg font-mono py-1 px-2 bg-white rounded border border-pink-200 shadow-sm">
                  {{ card }}
                </span>
              </div>
              <p class="text-sm text-gray-600">点数: <span class="font-bold">{{ bankerPoints }}</span></p>
            </div>
          </div>
        </div>
        
        <!-- 路单 -->
        <div class="mb-4">
          <h2 class="text-lg font-semibold mb-2 text-gray-700">路单</h2>
          <div class="bg-white/90 rounded-xl shadow-md p-3 h-full overflow-hidden">
            <div class="flex flex-nowrap gap-1 max-h-36 overflow-x-auto scrollbar-thin">
              <div v-for="(column, colIndex) in formattedRoadmap" :key="'col-'+colIndex" class="flex flex-col gap-1 flex-shrink-0">
                <div v-for="(result, rowIndex) in column" :key="'col-'+colIndex+'-row-'+rowIndex" 
                    class="w-8 h-8 flex items-center justify-center rounded-full"
                    :class="result === 'banker' ? 'bg-red-500 text-white' : (result === 'player' ? 'bg-blue-500 text-white' : 'bg-green-500 text-white')">
                  {{ result === 'banker' ? 'B' : (result === 'player' ? 'P' : 'T') }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 下注区域 -->
      <div class="mb-4">
        <h2 class="text-lg font-semibold mb-2 text-gray-700">下注</h2>
        <div class="grid grid-cols-3 gap-3 mb-2">
          <button 
            v-for="option in betOptions" 
            :key="option.value"
            @click="placeBet(option.value)"
            :class="[
              'py-2 rounded-xl font-bold transition-all duration-200 shadow',
              betChoice === option.value ? option.activeClass : option.baseClass
            ]"
          >
            {{ option.label }}
          </button>
        </div>
        <h3 class="text-sm font-semibold mb-1 text-gray-600">选择金额</h3>
        <!-- 注码选项分成3组显示 -->
        <div class="space-y-2 mb-2">
          <!-- 第一组注码 -->
          <div class="grid grid-cols-5 gap-2">
            <button 
              v-for="amount in betAmountOptions[0]" 
              :key="amount"
              @click="betAmount = amount; selectedBetGroup = 0;"
              :class="[
                'py-2 rounded-xl font-bold transition-all duration-200 shadow',
                betAmount === amount && selectedBetGroup === 0 ? 'bg-yellow-500 text-white' : (amount === 0 ? 'bg-gray-300 text-gray-700 hover:bg-gray-400' : 'bg-gray-100 text-gray-700 hover:bg-gray-200')
              ]"
            >
              {{ amount === 0 ? '观战' : amount }}
            </button>
          </div>
          
          <!-- 第二组注码 -->
          <div class="grid grid-cols-4 gap-2">
            <button 
              v-for="amount in betAmountOptions[1]" 
              :key="amount"
              @click="betAmount = amount; selectedBetGroup = 1;"
              :class="[
                'py-2 rounded-xl font-bold transition-all duration-200 shadow',
                betAmount === amount && selectedBetGroup === 1 ? 'bg-yellow-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              ]"
            >
              {{ amount }}
            </button>
          </div>
          
          <!-- 第三组注码 -->
          <div class="grid grid-cols-4 gap-2">
            <button 
              v-for="amount in betAmountOptions[2]" 
              :key="amount"
              @click="betAmount = amount; selectedBetGroup = 2;"
              :class="[
                'py-2 rounded-xl font-bold transition-all duration-200 shadow',
                betAmount === amount && selectedBetGroup === 2 ? 'bg-yellow-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              ]"
            >
              {{ amount }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 - 确保可见 -->
      <div class="flex justify-center space-x-4 mb-4 sticky bottom-4">
        <button 
          @click="startGame"
          class="px-5 py-2 bg-gradient-to-r from-green-400 to-green-500 text-white rounded-xl font-bold shadow hover:from-green-500 hover:to-green-600 transition-all duration-200"
        >
          开始新游戏
        </button>
        <button 
          @click="dealCards"
          class="px-5 py-2 bg-gradient-to-r from-blue-400 to-blue-500 text-white rounded-xl font-bold shadow hover:from-blue-500 hover:to-blue-600 transition-all duration-200"
        >
          发牌
        </button>
        <button 
          @click="clearAllHistory"
          class="px-5 py-2 bg-gradient-to-r from-red-400 to-red-500 text-white rounded-xl font-bold shadow hover:from-red-500 hover:to-red-600 transition-all duration-200"
        >
          清空历史
        </button>
      </div>
      
      <!-- 免佣百家乐规则说明 -->
      <div class="bg-white/80 rounded-xl shadow p-3 text-xs text-gray-700 mb-20">
        <h3 class="font-bold mb-1">免佣百家乐规则：</h3>
        <div class="grid grid-cols-2 gap-2">
          <ul class="list-disc ml-5 space-y-0">
            <li>庄家和闲家初始各发两张牌</li>
            <li>牌面计算：A为1点，2-9按牌面点数</li>
            <li>10和花牌为0点</li>
            <li>两张牌点数相加，取个位数为最终点数</li>
            <li>点数8或9为天牌，无需补牌</li>
          </ul>
          <ul class="list-disc ml-5 space-y-0">
            <li>闲家点数在0-5时补第三张牌</li>
            <li>庄家点数≤5且闲家未补牌时必须补牌</li>
            <li>庄家获胜赔率为1:1</li>
            <li>庄家以6点赢得游戏时，赔率为1:0.5</li>
            <li>闲家赔率1:1，和局赔率1:8</li>
          </ul>
        </div>
      </div>
    </div>
    
    <!-- 右侧历史记录 -->
    <div class="w-1/4 bg-white/70 shadow-xl p-4 overflow-auto max-h-screen">
      <h2 class="text-lg font-semibold mb-4 text-gray-700 sticky top-0 bg-white/90 py-2 border-b">历史记录</h2>
      
      <div v-if="history.length === 0" class="text-gray-400 text-center p-4">暂无记录</div>
      <div class="space-y-3">
        <div 
          v-for="(record, index) in history" 
          :key="index"
          class="p-3 rounded-xl shadow-md bg-gradient-to-r from-gray-50 to-gray-100 border border-gray-200"
        >
          <div class="flex justify-between items-center mb-2">
            <span class="font-mono text-xs text-gray-400">{{ record.timestamp }}</span>
            <span class="font-bold text-sm" 
                  :class="record.win_or_lose === 1 ? 'text-green-600' : (record.win_or_lose === 0 ? 'text-red-500' : 'text-gray-500')">
              <template v-if="record.win_or_lose === 1">
                +{{ (record.payout - record.bet_amount).toFixed(2) }}
              </template>
              <template v-else-if="record.win_or_lose === 0">
                -{{ record.bet_amount.toFixed(2) }}
              </template>
              <template v-else>
                0.00
              </template>
            </span>
          </div>
          <div class="flex justify-between mb-2 text-sm">
            <div>
              <span class="text-gray-600">下注: </span>
              <span class="font-bold">{{ translateResult(record.bet_choice) }}</span>
              <span class="ml-1">{{ record.bet_amount }}</span>
            </div>
            <div>
              <span class="text-gray-600">结果: </span>
              <span class="font-bold" :class="record.result === 'banker' ? 'text-red-500' : (record.result === 'player' ? 'text-blue-500' : 'text-green-500')">
                {{ translateResult(record.result) }}
              </span>
            </div>
          </div>
          <div class="grid grid-cols-2 gap-2 mt-2">
            <div class="bg-blue-50 p-2 rounded-lg">
              <p class="text-xs text-blue-700 font-semibold">闲家:</p>
              <p class="text-xs flex flex-wrap">
                <span v-for="(card, cIndex) in record.player_hand" :key="cIndex" 
                      class="inline-block mr-1 mb-1 px-1 bg-white/80 rounded border border-blue-100">
                  {{ card }}
                </span>
              </p>
              <p class="text-xs text-gray-500">点数: {{ record.player_points }}</p>
            </div>
            <div class="bg-pink-50 p-2 rounded-lg">
              <p class="text-xs text-pink-700 font-semibold">庄家:</p>
              <p class="text-xs flex flex-wrap">
                <span v-for="(card, cIndex) in record.banker_hand" :key="cIndex" 
                      class="inline-block mr-1 mb-1 px-1 bg-white/80 rounded border border-pink-100">
                  {{ card }}
                </span>
              </p>
              <p class="text-xs text-gray-500">点数: {{ record.banker_points }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 发牌动画组件 -->
    <CardAnimation 
      :showAnimation="showDealAnimation"
      :playerCards="playerHand"
      :bankerCards="bankerHand"
      :result="result"
      :win="win"
      :payout="payout"
      :betAmount="betAmount"
      :betChoice="betChoice"
      @close="closeDealAnimation"
    />
  </div>
</template>

<script>
import CardAnimation from '../components/CardAnimation.vue';
import api from '../logic/api';

export default {
  name: 'GamePage',
  components: {
    CardAnimation
  },
  data() {
    return {
      // 游戏状态
      playerHand: [],
      bankerHand: [],
      playerPoints: 0,
      bankerPoints: 0,
      betChoice: '',
      betAmount: 0,
      result: '',
      win: false,
      payout: 0,
      
      // 历史记录
      history: [],
      resultsHistory: [], // 不含和局的结果历史
      
      // 游戏控制
      showDealAnimation: false,
      totalWinLoss: 0,
      selectedBetGroup: 0,
      gameEnded: false,
      
      // 牌局管理
      cardsDealtCount: 0,
      maxCardsLimit: 400, // 默认400张牌的上限，相当于8副牌的77%
      
      // 下注选项配置
      betOptions: [
        { value: 'player', label: '闲', baseClass: 'bg-white text-blue-600 hover:bg-blue-50', activeClass: 'bg-blue-600 text-white' },
        { value: 'banker', label: '庄', baseClass: 'bg-white text-red-500 hover:bg-red-50', activeClass: 'bg-red-500 text-white' },
        { value: 'tie', label: '和', baseClass: 'bg-white text-green-600 hover:bg-green-50', activeClass: 'bg-green-600 text-white' }
      ],
      
      // 下注金额选项
      betAmountOptions: [
        [0, 100, 200, 500, 1000],
        [2000, 5000, 10000, 20000],
        [50000, 100000, 500000, 1000000]
      ]
    };
  },
  computed: {
    remainingDeals() {
      // 估算剩余可发牌次数，假设每局平均使用4-6张牌
      return Math.floor((this.maxCardsLimit - this.cardsDealtCount) / 5);
    },
    
    formattedRoadmap() {
      // 创建路单数据
      const results = this.resultsHistory.slice();
      const columns = [];
      let currentColumn = [];
      let lastResult = '';
      let sameCount = 0;
      
      for (const result of results) {
        if (result === lastResult) {
          // 如果与前一个结果相同，继续在同一列
          sameCount++;
          currentColumn.push(result);
        } else {
          // 不同结果，开始新列
          if (currentColumn.length > 0) {
            columns.push(currentColumn);
          }
          currentColumn = [result];
          lastResult = result;
          sameCount = 1;
        }
        
        // 列高度限制
        if (sameCount >= 6) {
          columns.push(currentColumn);
          currentColumn = [];
          lastResult = '';
          sameCount = 0;
        }
      }
      
      // 添加最后一列
      if (currentColumn.length > 0) {
        columns.push(currentColumn);
      }
      
      return columns;
    }
  },
  methods: {
    async fetchCardsStatus() {
      try {
        const data = await api.game.getCardsStatus();
        this.cardsDealtCount = data.cards_dealt || 0;
        this.maxCardsLimit = data.total_cards || 400;
        this.gameEnded = data.need_shuffle || false;
      } catch (error) {
        console.error('获取牌组状态失败:', error);
      }
    },
    
    async fetchHistory() {
      try {
        const data = await api.game.getHistory();
        this.history = data;
        
        // 提取不含和局的结果记录
        this.resultsHistory = data
          .filter(record => record.result !== 'tie')
          .map(record => record.result);
        
        // 计算总输赢
        this.totalWinLoss = data.reduce((total, record) => {
          if (record.win_or_lose === 1) {
            return total + record.payout;
          } else if (record.win_or_lose === 0) {
            return total - record.bet_amount;
          } else if (record.win_or_lose === 2) {
            // 和局情况下，庄闲下注返还本金，不输不赢
            return total;
          }
          return total;
        }, 0);
      } catch (error) {
        console.error('获取历史记录失败:', error);
      }
    },
    
    translateResult(result) {
      if (result === 'player') return '闲';
      if (result === 'banker') return '庄';
      if (result === 'tie') return '和';
      return '';
    },
    
    placeBet(choice) {
      if (this.gameEnded) {
        alert('游戏已结束，请开始新游戏');
        return;
      }
      this.betChoice = choice;
    },
    
    updateBetAmount(amount) {
      this.betAmount = amount;
    },
    
    async startGame() {
      // 开始新游戏，重置状态
      this.playerHand = [];
      this.bankerHand = [];
      this.playerPoints = 0;
      this.bankerPoints = 0;
      this.betChoice = '';
      this.betAmount = 0;
      this.result = '';
      this.win = false;
      this.payout = 0;
      this.gameEnded = false;
      this.cardsDealtCount = 0;
      
      try {
        // 通知后端重置牌堆
        await api.game.resetGame();
        this.fetchCardsStatus();
      } catch (error) {
        console.error('重置游戏失败:', error);
      }
    },
    
    async dealCards() {
      if (this.gameEnded) {
        alert('游戏已结束，请开始新游戏');
        return;
      }
      
      if (!this.betChoice && this.betAmount > 0) {
        alert('请选择下注方向');
        return;
      }
      
      try {
        // 发送下注和发牌请求
        const result = await api.game.deal({
          bet_choice: this.betChoice,
          bet_amount: this.betAmount
        });
        
        if (result.error) {
          alert(result.error);
          // 如果是牌不够，标记游戏结束
          if (result.error.includes('cards')) {
            this.gameEnded = true;
          }
          return;
        }
        
        // 更新游戏状态
        this.playerHand = result.player_hand || [];
        this.bankerHand = result.banker_hand || [];
        this.playerPoints = result.player_points || 0;
        this.bankerPoints = result.banker_points || 0;
        this.result = result.result || '';
        this.win = result.win || false;
        this.payout = result.payout || 0;
        
        // 更新牌组状态
        this.fetchCardsStatus();
        
        // 刷新历史记录
        this.fetchHistory();
        
        // 显示动画
        this.showDealAnimation = true;
      } catch (error) {
        console.error('发牌失败:', error);
      }
    },
    
    async clearAllHistory() {
      if (confirm('确定要清空所有历史记录吗？此操作不可恢复。')) {
        try {
          await api.game.clearHistory();
          this.fetchHistory();
        } catch (error) {
          console.error('清空历史失败:', error);
        }
      }
    },
    
    closeDealAnimation() {
      this.showDealAnimation = false;
    }
  },
  mounted() {
    this.fetchHistory();
    this.fetchCardsStatus();
  }
};
</script> 